package mercury;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import mercury.dao.CatalogException;
import mercury.util.Log;

public class TimexProperties extends AbstractCatalogProperties {

	private Log logger = new Log(this);
	private String prkeys = "";
	private int prkeyscount = 0;
	
	public TimexProperties(Map daoprops) {
		super(daoprops);		
	}
	
	public TimexProperties() {
		super();
	}

	public String getUnsynchedSessionsXMLFormat() {
		Map usfilter = new HashMap();
		usfilter.put("synchronized","0");
		String[][] unsynched = getSessions(usfilter);
		
		StringBuffer xml = new StringBuffer();
		xml.append("<data><sessions>");
		logger.info("Preparing Session:");
		for(int i=1;i<unsynched.length;i++) {
			String[] session = unsynched[i];
			xml.append("<session>");
			xml.append("<sessioninfo>");
			String id = "";
			String date = "";
			String infomsg = i + ")   ";
			for(int j=0;j<session.length;j++) {
					String key = unsynched[0][j];
					String value = unsynched[i][j];

					if(value == null || value.equals("null")) {
						value = "";
					}
					
					if(key.equals("prkey")) {
						id = value;
						key = "id";
						if(prkeys.length() > 0) {
							prkeys += ", ";
						}
						prkeys += value;
						prkeyscount = prkeyscount +1;
					}
					
					if(key.equals("session_datetime")) {
						key = "datetime";
						infomsg += "datetime="+value+";\t";
					}
					
					if(key.equals("session_date")) {
						try {
							DateFormat frm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					        Date d = (Date)frm.parse(value);
					        
					        DateFormat newfrm = new SimpleDateFormat("yyyy-MM-dd");
					        value = newfrm.format(d);
						} catch (ParseException e) {
							logger.error(e);
				        	logger.trace(e,e);
						}
						
						date = value;
						key = "date";
						infomsg += "date="+value+";\t";
					}
					
					if(key.equals("description")) {
						key = "notes";
					}
					
					if(key.equals("sport")) {
						Map slc = new HashMap();
						slc.put("table","SPORTS");
						slc.put("col:description","");
						slc.put("where:prkey",value);
						key = "activity";
						try {
							value = catalog.selectValue(slc);
						} catch (CatalogException e) {
							logger.error(e);
				        	logger.trace(e,e);
						}
						infomsg += "activity="+value+";\t";
					}
					
					
					
					if(key.equals("duration") || key.startsWith("time_zone")) { // convert to hh:mm:ss
						try {
							DateFormat secsfrm = new SimpleDateFormat("ss");
					        Date d = (Date)secsfrm.parse(value);
					        
					        DateFormat timefrm = new SimpleDateFormat("HH:mm:ss");
					        value = timefrm.format(d);
						} catch (ParseException e) {
							logger.error(e);
				        	logger.trace(e,e);
						}
						if(key.equals("duration")) {
							infomsg += "duration="+value+";\t";
						}
						
						if(key.startsWith("time_zone")) {
							String zone = key.substring("time_zone".length());
							key = "z" + zone + "_time";
						}
						
					}
					
					if(
							!key.equals("prkey") &&
							!key.equals("fromDataRecorder") &&
							!key.equals("Graph1") &&
							!key.equals("Graph2") &&
							!key.equals("Option1")
					) {
						xml.append("<" + key + ">" + value + "</" + key + ">");
					}
				}
				logger.info(infomsg);
				
				xml.append("</sessioninfo>");
				xml.append("<sessiondata>");
				String[][] sessdata = getSessionData(id);
				for(int j=1;j<sessdata.length;j++) {
					String[] record = sessdata[j];
					xml.append("<datarecord>");
					for(int k=0;k<record.length;k++) {
						String key = sessdata[0][k];
						String val = sessdata[j][k];
						
						if(key.equals("long")) {
							key = "lon";
						}
						
						if(!key.equals("prkey") && val != null && val.length() > 0) {
							xml.append("<" + key + ">" + val + "</" + key + ">");
						}
					}
					xml.append("</datarecord>");
				}
				xml.append("</sessiondata>");
				xml.append("<sessiondaily>");
				String[][] sessdaily = getDailyData(date);
				for(int j=1;j<sessdaily.length;j++) {
					String[] record = sessdaily[j];
					for(int k=0;k<record.length;k++) {
						String key = sessdaily[0][k];
						String val = sessdaily[j][k];
						
						if(!key.equals("prkey")) {
							if(key.equals("theday")) {
								val = date;
								key = "date";
							}
							
							xml.append("<" + key + ">" + val + "</" + key + ">");
						}
					}
					break;
				}
				
				xml.append("</sessiondaily>");
			xml.append("</session>");
		}		
		
		xml.append("</sessions>");
		
		Map sfilter = new HashMap();
		sfilter.put("synchronized","1");
		String[][] synched = getSessions(sfilter);
		String omitids = "";
		for(int i=1;i<synched.length;i++) {
			String[] session = synched[i];
			String id = "";	
			for(int j=0;j<session.length;j++) {
				String key = synched[0][j];
				String value = synched[i][j];
				if(key.equals("prkey")) {
					id = value;
				}
			}
			
			if(omitids.length() > 0) {
				omitids += ", ";
			}
			omitids += id;
			
		}
		
		xml.append("<omitsessions>" + omitids + "</omitsessions>");
		xml.append("</data>");
		
		return xml.toString();
	}
	
	private String[][] getSessions(Map filter) {
		Map slc = new HashMap();
		slc.put("table","SESSIONS");
		if(filter != null) {
			Object[] a = filter.keySet().toArray();
			for(int i=0;i<a.length;i++) {
				String key = (String) a[i];
				String val = (String) filter.get(key);
				if(!key.equals("table")) {
					slc.put("where:"+key,val);
				}
			}
		}

		try {
			return catalog.select(slc);
		} catch (CatalogException e) {
			logger.error(e);
        	logger.trace(e,e);
		}
		return null;
	}
	
	private String[][] getSessionData(String prkey) {
		Map slc = new HashMap();
		slc.put("table","SESSIONDATA");
		if(prkey != null) {
			slc.put("where:session_prkey",prkey);
			try {
				return catalog.select(slc);
			} catch (CatalogException e) {
				logger.error(e);
	        	logger.trace(e,e);
			}
		}
		
		return null;
	}
	
	private String[][] getDailyData(String date) {
		try {
			DateFormat secsfrm = new SimpleDateFormat("yyyy-MM-dd");
	        Date d = (Date)secsfrm.parse(date);
	        
	        DateFormat timefrm = new SimpleDateFormat("MM/dd/yyyy");
	        date = timefrm.format(d);
	        
	        Map slc = new HashMap();
			slc.put("table","DailyData");
			if(date != null) {
				slc.put("where:theday",date);
				return catalog.select(slc);
			}
		} catch (ParseException e) {
			logger.error(e);
        	logger.trace(e,e);
		} catch (CatalogException e) {
			logger.error(e);
        	logger.trace(e,e);
		}
		
		
		
		return null;
	}
	
	public int getSessionCount() {
		return prkeyscount;
	}
	
	public void updateSessionsStatus() {
		Map upd = new HashMap();
		upd.put("table","SESSIONS");
		upd.put("col:synchronized","1");
		upd.put("where_str:prkey","IN (" + prkeys+")");
		try {
			logger.info("Updating " + prkeyscount + " session(s) as synchronized");
			catalog.update(upd);
		} catch (CatalogException e) {
			logger.error(e);
        	logger.trace(e,e);
		}
	}
	
	public void close() {
		try {
			catalog.closeConnection();
		} catch (CatalogException e) {
			logger.error(e);
        	logger.trace(e,e);
		}
	}
}
